package com.study.spmongodb.threadlocal;

/**
 * @author study
 * @version 1.0
 * @date 2020/11/5 16:37
 */
public class ThreadLocalDemo {

    public static void main(String[] args) {

        // 定义ThreadLocal
        ThreadLocal<String> threadLocal = new ThreadLocal<String>() {
            @Override
            protected String initialValue() {
                return "init value.";
            }
        };

        // 启动线程A
        new Thread(() -> {
            // set的过程实际上是对当前Thread类实例对象中的属性值threadLocals进行赋值
            // 值为 new ThreadLocalMap(this, firstValue);
            // 其中的this是当前的threadLocal实例对象
            threadLocal.set("我是线程A.");

            // get的过程实际上是先获取当前的线程, 然后获取当前线程中的threadLocals属性值(ThreadLocalMap)
            // 然后通过key来获取值, key就是当前的实例对象, 也就是threadLocal实例对象
            System.out.println(Thread.currentThread().getName() + ": " + threadLocal.get());

            // 移除
            threadLocal.remove();
        }, "线程A").start();

        // 启动线程B
        new Thread(() -> {
            threadLocal.set("我是线程B.");
            System.out.println(Thread.currentThread().getName() + ": " + threadLocal.get());
            threadLocal.remove();
        }, "线程B").start();

        // 打印主线程中的值
        System.out.println(Thread.currentThread().getName() + ": " + threadLocal.get());
        threadLocal.remove();

    }
}
